Page({
	data: {
		coupons: [],
		page: 0,
		couponSn: undefined,
	},
	onLoad: function({ couponSn }) {
		const { userId = "" } = wx.getStorageSync("userInfo");
		if(!userId) {
			wx.navigateTo({
				url: '../login/login'
			})
			return;
		}
		
		if(this.data.couponSn) {
			this.initCouponDetails();
		} else {
			this.initCoupon();
		}
		this.initCoupon();
		//this.initCouponDetails();
	},
	
	initCouponDetails() {
		const that = this;
		const { userId = "" } = wx.getStorageSync("userInfo");
		if(userId) {
			// wx.request({
			// 	url:'https://pms.uxon.net/api/miniapp/coupon/findByCouponSn',
			// 	method: "GET",
			// 	data: {
			// 		couponSn: that.data.couponSn
			// 	},
			// 	success:function(res) {
			// 		console.log(res)
			// 	}
			// })
		}
	},
	initCoupon() {
		const that = this;
		const { userId = "" } = wx.getStorageSync("userInfo");
		if(userId) {
			wx.request({
				url:'https://pms.uxon.net/api/miniapp/coupon/page',
				method:"GET",
				data:{
					page: that.data.page,
					size: 10,
				},
				header: {
					"content-type": "application/x-www-form-urlencoded", //修改此处即可
				},
				success:function(res) {
					const data = res.data.data.content;
					data.forEach((val) => {
						val.startTime = val.startTime.split(" ")[0];
						val.expireTime = val.expireTime.split(" ")[0];
					})
					that.setData({
						coupons:that.data.page === 0 ? data : that.data.coupons.concat(data)
					})
				}
			})
		}
	},
	onReceive(options) {
		const { userId = "" } = wx.getStorageSync("userInfo");
		const couponSn = options.currentTarget.dataset.item.couponSn;
		const id = options.currentTarget.dataset.item.id;
		wx.request({
			url:"https://pms.uxon.net/api/miniapp/couponUser/page",
			method:"POST",
			data: {
				couponSn,
				userId
			},
			header: {
				"content-type": "application/x-www-form-urlencoded", //修改此处即可
			},
			success:function(res) {
				if (res.data.data.content.length > 0) {
					wx.showToast({
					  title: "你已经领取过了",
					  icon: "none",
					  duration: 2000,
					});
				} else {
					wx.request({
						url:'https://pms.uxon.net/api/miniapp/couponUser',
						method: "PUT",
						data: {
							couponSn,
							id,
							remark: "",
							status: 0,
							userId,
						},
						success:function(res) {
							wx.navigateTo({
								url: `../couponSuccess/couponSuccess?couponSn=${couponSn}`,
							});
						}
					})
				}	
			}
		})
	},
	
	async onReachBottom() {
		this.data.page += 1;
		this.initCoupon();
	}
})
